// pages/bar/bar.js

// 引入wx-charts.js文件
const CHARTS = require('../../utils/wxcharts.js');
// 获取微信小程序实例
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        //   记得的单词数量
        re: null,
        // 忘记的单词数量
        fg: [],
        // 一周的日期
        List: [],
        //前段日期
        List1: [],
        // 后段日期
        List2: [],
        //js格式的一周日期
        js_List: [],
        js_List1: [],
        js_List2: [],
        // 不是周一时计算出的周一
        Monday: '',
        //上周周一
        last_monday: '',
        // 下周周一
        next_monday: '',
        // 判断选择的是上一周还是下一周
        check: 3,
        //用来改变的day
        ch_day: null,
        // 计算一共有几周的数据
        count: 0,
        // monday_id数组
        mon_id: [],
        // monday_id数组下标
        n: 0,
        // 判断数据是否为空
        nullNot:0,
    },


    onLoad: function (e) {
        // 获取今天的日期
        var day = new Date()
        var record = wx.getStorageSync("record");
        this.setData({
            day: day,
            ch_day: day,
            ch2_day: day,
            re: record,
        })
        this.week_day(day);
        this.draw();

        // this.getrecord();

    },

    //初始化函数
    intelize: function () {
        var t = new Date()
        var week = this.week(t)
        var id = null
        var nullNot
        // var last_day=t.setDate(t.getDate()-1);
        // last_day=new Date(last_day);
        console.log("re:", this.data.re);
        for (var i in this.data.re) {
            if (this.data.re[i].day == this.formatDate(t)) {
                console.log("day", i);
                id = i
            }
        }
        if (id == null && this.data.re != '') {
            id = this.data.re.length * 1 - 1
            console.log("之前学了但是今天没有学习：", id);
        } else if (this.data.re == '') {
            id = -1
        }
        console.log("t:", this.formatDate(t))
        console.log("下标为：", id)
        if(this.data.re.length!=0){
            var next_mondayid
            //第一周的数据不足一周时的判断 
                if (this.data.re[0].day != this.data.List[6]) {
                    for (var i in this.data.List) {
                        if (this.data.List[i] == this.data.re[0].day) {
                            next_mondayid = 8 - i;
                            break;
                        }
                    }
                } else {
                    next_mondayid = 1;
                }
    
            var monday_id
            // 如果首周的数据第一天不是周一且数据的长度小于有下一个周一的长度时
                if (this.data.re[0].day != this.data.List[0] && this.data.re.length < next_mondayid * 1 + 1) {
                    monday_id = 0;
                } else {
                    monday_id = id - (week * 1 - 1);
                }
    
                nullNot=0
        }else{
            nullNot=1
        }
        this.setData({
            monday_id: monday_id,
            nullNot:nullNot,
        })
        console.log("nullNot",this.data.nullNot)

        var count = this.data.count;
        //计算一共有几个周的数据
        while (monday_id != 0) {
            if (monday_id - 7 > 0) {
                count++;
                monday_id = monday_id - 7;
                console.log('id:', monday_id)
            } else {
                count++;
                monday_id = 0;
                console.log('id:', monday_id)
            }
        }
        this.setData({
            count: count
        })
        // 获取数据中周一的id值存入数组
        // var mon_id=this.data.mon_id;
        var mon_id = [];
        for (var i = 0; i <= this.data.count; i++) {
            // var record='mon_id['+ i+']'
            if (this.data.monday_id * 1 - 7 > 0) {
                // this.setData({
                //     [record]:{}
                // })
                mon_id[i] = this.data.monday_id
                this.setData({
                    monday_id: this.data.monday_id * 1 - 7,
                })
            } else {
                mon_id[i] = this.data.monday_id
                this.setData({
                    monday_id: 0,
                })
            }
        }
        this.setData({
            mon_id: mon_id,
        })
        return {
            monday_id: monday_id,
            week: week,
        }

    },
    // 图表数据创建
    createData: function () {
        // x轴的坐标数据
        var categories = [];
        // 记得的图表数据
        var data = []
        // 不记得的图表数据
        var data2 = []

        for (var i = 0; i < 7; i++) {
            categories.push(this.data.List[i].day);
        }

        //last_week数据 
        if (this.data.check == 0) {
            // mon_id数组下标位置
            var j = this.data.n * 1 - 1
            var n = this.data.mon_id[j];
            console.log("last_week")
            // console.log("n:", n);
            if (n * 1 - 7 > 0) {
                var Array = this.data.re.slice(n * 1 - 7, n);
                console.log("Array", Array);
                this.setData({
                    monday_id: this.data.monday_id * 1 - 7,
                    Array: Array,
                })
                // for (var i in Array) {
                //     data[i] = Array[i].re
                //     data2[i]=Array[i].fg
                // }
                for (var i in Array) {
                    for (var j = 0; j < 7; j++) {
                        if (this.data.List[j].day == this.data.Array[i].day) {
                            console.log('Array每项数据', this.data.Array[i].day);
                            console.log("赋值下标：", j);
                            data[j] = Array[i].re;
                            data2[j] = Array[i].fg;
                        } else {
                            if (data[j] == null) {
                                data[j] = null;
                                data2[j] = null;
                                console.log("空值下标：", j)
                            }


                        }
                    }

                }
            } else {
                var Array = this.data.re.slice(0, n);
                console.log("Arry", Array);
                // for (var i = 0; i < 7; i++) {
                //     if (n * 1 + i <= 6) {
                //         data[i] = null;
                //         data2[i]=null;
                //     } else {
                //         data[i] = Array[i - (7 - n * 1)].re
                //         data2[i] = Array[i - (7 - n * 1)].fg
                //     }
                // }
                this.setData({
                    monday_id: 0,
                    Array: Array,
                })
                for (var i in Array) {
                    for (var j = 0; j < 7; j++) {
                        if (this.data.List[j].day == this.data.Array[i].day) {
                            console.log('Array每项数据', this.data.Array[i].day);
                            console.log("赋值下标：", j);
                            data[j] = Array[i].re;
                            data2[j] = Array[i].fg;
                        } else {
                            if (data[j] == null) {
                                data[j] = null;
                                data2[j] = null;
                                console.log("空值下标：", j)
                            }


                        }
                    }

                }

            }
        } else if (this.data.check == 1) {
            console.log("next_week")
            // next_week数据
            // mon_id数组下标位置
            var j = this.data.n * 1
            var n = this.data.mon_id[j];
            console.log("n:", n);
            // if (this.data.re.length > n * 1 + 7) {
            var Array = this.data.re.slice(n, n * 1 + 7);
            // console.log("Array", Array);
            // for (var i in Array) {
            //     data[i] = Array[i].re
            //     data2[i] = Array[i].fg
            // }
            this.setData({
                monday_id: this.data.monday_id * 1 + 7,
                Array: Array,
            })
            for (var i in Array) {
                for (var j = 0; j < 7; j++) {
                    if (this.data.List[j].day == this.data.Array[i].day) {
                        console.log('Array每项数据', this.data.Array[i].day);
                        console.log("赋值下标：", j);
                        data[j] = Array[i].re;
                        data2[j] = Array[i].fg;
                    } else {
                        if (data[j] == null) {
                            data[j] = null;
                            data2[j] = null;
                            console.log("空值下标：", j)
                        }


                    }
                }

            }
        } else {
            console.log("初始化")
            // 初始化数据
            var n = this.intelize()
            // 如果有数据的话
            console.log('n.monday_id-------------', n.monday_id)
            if (n.monday_id >= 0&&this.data.nullNot==0) {
                var Array = this.data.re.slice(n.monday_id, n.monday_id * 1 + 7);
                var Array_day = [];
                for (var i in Array) {
                    Array_day[i] = Array[i].day
                }
                this.setData({
                    Array: Array,
                    Array_day: Array_day,
                })
                for (var i in Array) {
                    for (var j = 0; j < 7; j++) {
                        if (this.data.List[j].day == this.data.Array[i].day) {
                            console.log('Array每项数据', this.data.Array[i].day);
                            console.log("赋值下标：", j);
                            data[j] = Array[i].re;
                            data2[j] = Array[i].fg;
                        } else {
                            if (data[j] == null) {
                                data[j] = null;
                                data2[j] = null;
                                console.log("空值下标：", j)
                            }


                        }
                    }

                }
            }else {
                for (var i = 0; i < 7; i++) {
                    data[j] = 0;
                    data2[j] = 0;
                }
                console.log(data)
                console.log(data2)
                wx.showModal({
                    title: '提示',
                    content: '还没有学习数据',
                    showCancel: true,
                    cancelText: '取消',
                    cancelColor: '#000000',
                    confirmText: '确定',
                    confirmColor: '#3CC51F',
                    success: (result) => {},
                    fail: () => {},
                    complete: () => {}
                });
            }
        }

        console.log("monday_id", n.monday_id);
        return {
            categories: categories,
            data: data,
            data2: data2,
        }

    },

    // 画图表
    draw: function (re, fg) {
        var windowWidth = '',
            windowHeight = ''; //定义宽高
        try {
            var res = wx.getSystemInfoSync(); //试图获取屏幕宽高数据
            windowWidth = res.windowWidth*0.9;
            windowHeight = res.windowWidth / 320 * 250 //以宽度为320的机型为主进行比例算换
            console.log("宽度", windowWidth)
        } catch (e) {
            console.error('getSystemInfoSync failed!'); //如果获取失败
        }
        // 图表的数据
        var simulation_Data = this.createData();
        var n = this.intelize();
        var data1 = []
        var data2 = []
        console.log("下标:", n.monday_id);
        if (n.monday_id >= 0&&this.data.nullNot==0) {
            data1 = simulation_Data.data;
            data2 = simulation_Data.data2;
            // data1=[0,0,0,0,0,0,0]
            // data2=[0,0,0,0,0,0,0]
        } else {
            data1 = [0, 0, 0, 0, 0, 0, 0]
            data2 = [0, 0, 0, 0, 0, 0, 0]
        }
        console.log("x轴数据", simulation_Data.categories);
        console.log("y轴数据", data1)
        var lineShow = null
        lineShow = new CHARTS({
            // 画布id
            canvasId: 'lineGraph',
            // 图表类型
            type: 'line',
            // x轴数据
            categories: simulation_Data.categories,
            // 是否动态展示
            animation: true,
            // 数据列表
            series: [{
                name: '认识的单词',
                data: data1,
            }, {
                name: '不认识的单词',
                data: data2,
            }],
            // x轴配置
            xAxis: {
                // 不绘制X轴网格
                disableGrid: false
            },
            // y轴配置
            yAxis: {
                title: '单词个数（个）',
                // y轴起点
                min: 0,
            },
            // 宽度单位px
            width: windowWidth,
            // 高度单位px
            height: windowHeight,
            // 是否在图表中显示数据内容
            dataLabel: true,
            // 是否在图表中显示数据点图形标识
            dataPointShape: true,
            // 动画展示数据
            animation: true,
            extra: {
                lineStyle: 'straight'
            }


        })
    },
    // 判断当前日期是星期几
    week: function (e) {
        var day = e
        var a = new Array("日", "一", "二", "三", "四", "五", "六");
        var week = new Date(day).getDay();
        var str = "今天是星期" + a[week];
        console.log("今天是", day);
        console.log(str);
        // 返回星期几
        return week;
    },
    // 日期格式转换函数
    formatDate: function (date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? '0' + m : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + '-' + m + '-' + d;
    },
    // 显示今天所属一周的日期
    week_day: function (e) {
        var week = this.week(e);
        var js_List
        var record
        console.log("week:", week);
        // 如果是周一的话
        if (week == 1) {
            var List = this.data.List;
            for (var i = 0; i < 7; i++) {
                var record = 'List[' + i + ']'
                var js_List = 'js_List[' + i + ']'
                var day = this.data.day;
                // console.log("新增日期：",this.formatDate(add_day));
                this.setData({
                    [record]: {
                        day: this.formatDate(day)
                    },
                    [js_List]: {
                        day: day
                    }
                })
                var add_day = day.setDate(day.getDate() + 1);
                add_day = new Date(add_day)
                this.setData({
                    day: add_day,
                })
            }
        } else {
            var List1 = this.data.List1
            var List2 = this.data.List2
            var day = new Date();
            if (week == 0) {
                week = 7
            }
            console.log("day-----------------:", day);
            var subt_day = day.setDate(day.getDate() - (week * 1 - 1));
            subt_day = new Date(subt_day)
            console.log("Monday--------------:", subt_day);
            this.setData({
                Monday: subt_day,
            })
            // 今天之前
            for (var i = 0; i <= week * 1 - 1; i++) {
                var day1 = this.data.Monday
                var js_List1 = 'js_List1[' + i + ']'
                var record = 'List1[' + i + ']'
                console.log("day:", this.formatDate(day1));
                this.setData({
                    [record]: {
                        day: this.formatDate(day1)
                    },
                    [js_List1]: {
                        day: day1
                    }
                })
                var add_day = day.setDate(day.getDate() + 1);
                add_day = new Date(add_day)
                this.setData({
                    Monday: add_day,
                })

            }

            // 今天之后
            for (var i = 0; i < 7 - week * 1; i++) {
                var day1 = this.data.Monday
                var js_List2 = 'js_List2[' + i + ']'
                var record = 'List2[' + i + ']'
                console.log("day:", this.formatDate(day1));
                this.setData({
                    [record]: {
                        day: this.formatDate(day1)
                    },
                    [js_List2]: {
                        day: day1
                    }
                })
                var add_day = day.setDate(day.getDate() + 1);
                add_day = new Date(add_day)
                this.setData({
                    Monday: add_day,
                })
            }
            // 合并前后段日期
            var List = this.data.List1.concat(this.data.List2)
            var js_List = this.data.js_List1.concat(this.data.js_List2)
            this.setData({
                List: List,
                js_List: js_List,
            })
        }

    },
    // 上一周
    last_week: function () {
        var nowday = this.data.ch_day
        console.log("nowday", this.formatDate(nowday));
        // console.log("this.data.re[0].day", this.data.re[0].day);
        var n = this.intelize();
        var re0_day
        if (n.monday_id > 0) {
            re0_day = this.data.re[0].day;
        } else {
            re0_day = this.formatDate(nowday);
        }
        if (this.formatDate(nowday) != re0_day) {
            var lastday = nowday.setDate(nowday.getDate() - 7)
            lastday = new Date(lastday)
            console.log('lastday', this.formatDate(nowday));
            console.log('last', this.data.re[0].day)
            var last_monday = this.data.js_List1[0].day
            var subt_day = last_monday.setDate(last_monday.getDate() - 7);
            subt_day = new Date(subt_day)
            this.setData({
                last_monday: subt_day,
                day: subt_day,
                check: 0,
                ch_day: lastday,
                n: this.data.n * 1 + 1
            })
            this.week_day(last_monday);
        } else {
            wx.showModal({
                title: '提示',
                content: '已经是最早的数据了',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#000000',
                confirmText: '确定',
                confirmColor: '#3CC51F',
                success: (result) => {},
                fail: () => {},
                complete: () => {}
            });
        }
        this.draw();
    },
    // 下一周
    next_week: function () {
        var len = this.data.re.length
        var nowday = this.data.ch_day
        var n = this.intelize();
        var re0_day
        if (n.monday_id > 0) {
            re0_day = this.data.re[len * 1 - 1].day;
        } else {
            re0_day = this.formatDate(nowday);
        }
        if (this.formatDate(nowday) != re0_day) {
            var today = nowday.setDate(nowday.getDate() + 7)
            today = new Date(today)
            var next_monday = this.data.js_List1[0].day
            var add_day = next_monday.setDate(next_monday.getDate() + 7);
            add_day = new Date(add_day)
            this.setData({
                next_monday: add_day,
                day: add_day,
                check: 1,
                ch_day: today,
                n: this.data.n * 1 - 1,
            })
            this.week_day(next_monday);
        } else {
            wx.showModal({
                title: '提示',
                content: '已经是最新的数据了',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#000000',
                confirmText: '确定',
                confirmColor: '#3CC51F',
                success: (result) => {},
                fail: () => {},
                complete: () => {}
            });
        }
        this.draw();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

        // 获取数据库中的数据
        getrecord:function(){
            const db = wx.cloud.database();
            // 获取此次用户的openid
            var _openid = wx.getStorageSync("_openid");
            // 获取数据库中用户的应用数据
            db.collection('userData').where({
              _openid: _openid,
            }).get({
              success: res => {
                console.log(res)
                this.setData({
                  re: res.data[0].record,
        
                })
                    console.log("数组数据：",this.data.re);
                  }
                })
              }, 
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            re: wx.getStorageSync("record"),
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})